#include "memcached_db.h"
#include <cstring>
#include<pthread.h>
using namespace std;
namespace ycsbc{
thread_local static memcached_st *thlc_memc_;
void MemcachedDB::Init(){
    auto tmpm=memcached(cfg_string.c_str(),cfg_string.size());
    assert(tmpm != NULL);
    memc_[__sync_fetch_and_add(&cnt_,1)] = tmpm;
    thlc_memc_ = tmpm;
    //cout << "Create MemcachedDB" << endl;
}


int MemcachedDB::Read(const std::string &table, const std::string &key, const std::vector<std::string> *fields, std::vector<KVPair> &result){
    size_t v_len;
    uint32_t flags;
    memcached_return_t rc;
    auto val=memcached_get(thlc_memc_,key.c_str(),key.size(),&v_len,&flags,&rc);
    assert(rc==MEMCACHED_SUCCESS);
    string ret=string(val,v_len);
    result.push_back(make_pair(key,ret));
    return DB::kOK;
}

int MemcachedDB::Update(const std::string &table, const std::string &key, std::vector<KVPair> &values){
    auto val=values[0].second;
    auto rc=memcached_set(thlc_memc_,key.c_str(),key.length(),val.c_str(),val.size(),(time_t)0,(uint32_t)0);
    assert(rc==MEMCACHED_SUCCESS);
    return DB::kOK;
}

int MemcachedDB::Delete(const std::string &table, const std::string &key){
    auto rc=memcached_delete(thlc_memc_,key.c_str(),key.size(),(time_t)0);
    assert(rc==MEMCACHED_SUCCESS);
    return DB::kOK;
}

}